// src/App.tsx
import React, { useState, useEffect, useRef } from "react";

import GroupInfo from "./components/GroupInfo";
import GroupAvatar from "./components/GroupAvatar";
import EmojiPicker from "./components/EmojiPicker";
import MessageOpMenu from "./components/MessageOpMenu";
import MessageInput from "./components/MessageInput";
import MessageDisplay from "./components/MessageDisplay";

import groups from "./mock/groups";
import friends from "./mock/friends";
import type { Group, Message } from "./mock/types";
import {
  generateInitialMessages,
  generateRandomGroupMessage,
} from "./mock/utils";

const ChatApp = () => {
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const [currentGroup, setCurrentGroup] = useState<Group>(groups[0]);
  const [messages, setMessages] = useState<Message[]>(
    generateInitialMessages()
  );
  const [newMessage, setNewMessage] = useState<string>("");
  const [isPlusMenuOpen, setIsPlusMenuOpen] = useState<boolean>(false);
  const [isEmojiPickerOpen, setIsEmojiPickerOpen] = useState<boolean>(false);
  const [activeMessageId, setActiveMessageId] = useState<string | null>(null);
  const [isTextInputFocused, setIsTextInputFocused] = useState<boolean>(true);
  const [touchPosition, setTouchPosition] = useState({ x: 0, y: 0 });
  const chatEndRef = useRef<HTMLDivElement>(null);
  const chatContainerRef = useRef<HTMLDivElement>(null);
  const menuRef = useRef<HTMLDivElement>(null);
  const emojiPickerRef = useRef<HTMLDivElement>(null);
  const textareaRef = useRef<HTMLTextAreaElement>(null);
  const emojiButtonRef = useRef<HTMLButtonElement>(null);

  // 用于存储触摸计时器
  const touchTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  // 用于检测是否在滚动
  const isScrollingRef = useRef(false);

  // 标记是否长按生效
  const longPressActivatedRef = useRef(false);

  const me = friends.find((f) => f.name === "乐呗")!;

  // 滚动到最新消息
  const scrollToBottom = () => {
    chatEndRef.current?.scrollIntoView({ behavior: "smooth" });
  };

  useEffect(() => {
    scrollToBottom();

    // 添加滚动事件监听
    const handleScroll = () => {
      isScrollingRef.current = true;
      // 关闭菜单
      if (activeMessageId) setActiveMessageId(null);
      if (isEmojiPickerOpen) setIsEmojiPickerOpen(false);

      // 500ms后重置滚动状态
      clearTimeout(touchTimerRef.current as ReturnType<typeof setTimeout>);
      touchTimerRef.current = setTimeout(() => {
        isScrollingRef.current = false;
      }, 500);
    };

    const container = chatContainerRef.current;
    if (container) {
      container.addEventListener("scroll", handleScroll);
    }

    // 添加全局点击监听来关闭菜单和表情选择器
    const handleClickOutside = (event: MouseEvent) => {
      const target = event.target as HTMLElement;

      // 如果点击的是表情按钮，不关闭表情选择器
      if (emojiButtonRef.current?.contains(target)) {
        return;
      }

      // 关闭消息操作菜单
      if (
        activeMessageId &&
        menuRef.current &&
        !menuRef.current.contains(target)
      ) {
        setActiveMessageId(null);
      }

      // 关闭表情选择器
      if (
        isEmojiPickerOpen &&
        emojiPickerRef.current &&
        !emojiPickerRef.current.contains(target)
      ) {
        setIsEmojiPickerOpen(false);
      }

      // 关闭附加功能菜单
      if (isPlusMenuOpen && !target.closest(".plus-menu-container")) {
        setIsPlusMenuOpen(false);
      }
    };

    document.addEventListener("mousedown", handleClickOutside);
    document.addEventListener("touchstart", handleClickOutside as any);
    // 处理触摸事件

    return () => {
      if (container) {
        container.removeEventListener("scroll", handleScroll);
      }
      // 清除定时器
      if (touchTimerRef.current) {
        clearTimeout(touchTimerRef.current);
      }

      document.removeEventListener("mousedown", handleClickOutside);
      document.removeEventListener("touchstart", handleClickOutside as any);
    };
  }, [messages, activeMessageId, isEmojiPickerOpen, isPlusMenuOpen]);

  // 模拟其他群成员发言 - 随机添加表情
  useEffect(() => {
    const interval = setInterval(() => {
      if (messages.length < 15 && Math.random() > 0.3) {
        const newMsg = generateRandomGroupMessage(me.name);

        setMessages((prev) => [...prev, newMsg]);
      }
    }, 15000); // 每15秒可能有新消息

    return () => clearInterval(interval);
  }, [messages]);

  // 发送消息
  const handleSendMessage = () => {
    if (newMessage.trim() === "") return;

    const isEmojiOnly = /^(\p{Emoji}+)$/u.test(newMessage.trim());

    const newMsg: Message = {
      id: `m${Date.now()}`,
      sender: me,
      content: newMessage.trim(),
      time: new Date().toTimeString().substring(0, 5),
      type: isEmojiOnly ? "emoji" : "text",
      isMine: true,
    };

    setMessages([...messages, newMsg]);
    setNewMessage("");
    setIsPlusMenuOpen(false);
    setIsEmojiPickerOpen(false);
    setActiveMessageId(null);

    // 发送后重新聚焦输入框
    if (textareaRef.current) {
      textareaRef.current.focus();
    }
  };

  // 处理键盘事件（Enter发送）
  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      handleSendMessage();
    }
  };

  // 消息操作（删除消息）
  const handleDeleteMessage = (id: string) => {
    setMessages(messages.filter((msg) => msg.id !== id));
    setActiveMessageId(null);
  };

  // 处理触摸开始 - 长按消息 (关键修复)
  const handleTouchStart = (e: React.TouchEvent, messageId: string) => {
    if (isScrollingRef.current) return;
    const touch = e.touches[0];
    setTouchPosition({ x: touch.pageX, y: touch.pageY }); // 用 pageX/pageY
    longPressActivatedRef.current = false;
    if (touchTimerRef.current) clearTimeout(touchTimerRef.current);
    touchTimerRef.current = setTimeout(() => {
      longPressActivatedRef.current = true;
      showContextMenu(messageId, touch.pageX, touch.pageY); // 用 pageX/pageY
    }, 500);
  };

  // 处理触摸移动 - 防止滑动时触发长按
  const handleTouchMove = (e: React.TouchEvent) => {
    if (!touchTimerRef.current) return;

    const touch = e.touches[0];
    const dx = Math.abs(touch.clientX - touchPosition.x);
    const dy = Math.abs(touch.clientY - touchPosition.y);

    // 如果移动距离超过10像素，取消长按
    if (dx > 10 || dy > 10) {
      clearTimeout(touchTimerRef.current);
      touchTimerRef.current = null;
      longPressActivatedRef.current = false;
    }
  };

  // 处理触摸结束
  const handleTouchEnd = () => {
    if (touchTimerRef.current) {
      clearTimeout(touchTimerRef.current);
      touchTimerRef.current = null;
    }
  };

  // 显示上下文菜单 (关键修复)
  const showContextMenu = (messageId: string, x: number, y: number) => {
    setActiveMessageId(null);
    setTouchPosition({ x, y }); // 这里的 x/y 已是 pageX/pageY
    setActiveMessageId(messageId);
  };

  // 计算菜单位置
  const getMenuStyle = () => {
    if (!chatContainerRef.current || !activeMessageId) return {};
    const containerRect = chatContainerRef.current.getBoundingClientRect();

    // 用 pageX/pageY - 容器的left/top 得到相对容器的坐标
    const left = Math.min(
      Math.max(touchPosition.x - containerRect.left - window.scrollX, 10),
      containerRect.width - 150
    );
    const top = Math.min(
      Math.max(touchPosition.y - containerRect.top - window.scrollY, 10),
      containerRect.height - 150
    );
    return {
      position: "absolute",
      top: `${top}px`,
      left: `${left}px`,
      zIndex: 50,
    };
  };

  // 处理表情选择
  const handleEmojiSelect = (emoji: string) => {
    setNewMessage((prev) => prev + emoji);

    // 选择表情后自动聚焦到输入框
    if (textareaRef.current) {
      textareaRef.current.focus();
    }

    // 切换回文本输入模式
    setIsTextInputFocused(true);
  };

  // 点击附加功能时关闭其他菜单
  const handleAdditionalFeatureClick = (feature: string) => {
    console.log(`打开${feature}`);
    setIsPlusMenuOpen(false);
    setIsEmojiPickerOpen(false);
    setActiveMessageId(null);
  };

  // 切换表情选择器
  const toggleEmojiPicker = () => {
    // 如果输入框处于语音输入状态，先切换回文本输入
    if (!isTextInputFocused) {
      setIsTextInputFocused(true);

      // 延迟一点确保DOM更新完成再聚焦输入框
      setTimeout(() => {
        if (textareaRef.current) {
          textareaRef.current.focus();
        }
      }, 50);
    }

    setIsEmojiPickerOpen(!isEmojiPickerOpen);
    setIsPlusMenuOpen(false);
    setActiveMessageId(null);

    // 确保输入框处于激活状态
    setIsTextInputFocused(true);

    // 延迟一点确保DOM更新完成再聚焦输入框
    setTimeout(() => {
      if (textareaRef.current) {
        textareaRef.current.focus();
      }
    }, 50);
  };

  // 处理输入框聚焦
  const handleFocusInput = () => {
    setIsTextInputFocused(true);
    setActiveMessageId(null);
    setIsEmojiPickerOpen(false);

    // 如果需要，可以在这里显示键盘（在移动设备上）
    if (textareaRef.current) {
      textareaRef.current.focus();
    }
  };

  return (
    <div className="flex flex-col h-screen max-w-md mx-auto bg-gray-100 font-sans">
      {/* 顶部导航栏 */}
      {/* 群组信息 */}
      <GroupInfo
        group={currentGroup}
        onMore={() => {
          console.log("打开设置");
          setActiveMessageId(null);
          setIsEmojiPickerOpen(false);
          setIsPlusMenuOpen(false);
        }}
      />
      {/* 群组头像显示 */}
      <div className="flex justify-center py-2 bg-green-500">
        <GroupAvatar members={currentGroup.members} />
      </div>

      {/* 消息区域 */}
      <div
        ref={chatContainerRef}
        className="flex-1 overflow-y-auto bg-gray-100 p-4 space-y-4 relative"
        onClick={() => {
          setActiveMessageId(null);
          setIsEmojiPickerOpen(false);
        }}
      >
        <MessageDisplay
          messages={messages}
          chatContainerRef={chatContainerRef}
          chatEndRef={chatEndRef}
          menuRef={menuRef}
          activeMessageId={activeMessageId}
          getMenuStyle={getMenuStyle}
          showContextMenu={showContextMenu}
          handleTouchStart={handleTouchStart}
          handleTouchMove={handleTouchMove}
          handleTouchEnd={handleTouchEnd}
          handleDeleteMessage={handleDeleteMessage}
          setActiveMessageId={setActiveMessageId}
          setIsEmojiPickerOpen={setIsEmojiPickerOpen}
          MessageOpMenu={MessageOpMenu}
        />

        {/* 消息操作菜单 */}
        {activeMessageId && (
          <MessageOpMenu
            menuRef={menuRef}
            style={getMenuStyle()}
            onReply={() => {
              console.log("回复消息");
              setActiveMessageId(null);
            }}
            onForward={() => {
              console.log("转发消息");
              setActiveMessageId(null);
            }}
            onDelete={(e) => {
              e.stopPropagation();
              handleDeleteMessage(activeMessageId);
            }}
          />
        )}

        <div ref={chatEndRef} />
      </div>

      {/* 表情选择器 */}
      {isEmojiPickerOpen && (
        <div ref={emojiPickerRef} className="absolute bottom-20 left-4 z-50">
          <EmojiPicker onSelect={handleEmojiSelect} />
        </div>
      )}

      {/* 底部输入区域 */}
      <MessageInput
        newMessage={newMessage}
        setNewMessage={setNewMessage}
        isPlusMenuOpen={isPlusMenuOpen}
        setIsPlusMenuOpen={setIsPlusMenuOpen}
        isEmojiPickerOpen={isEmojiPickerOpen}
        setIsEmojiPickerOpen={setIsEmojiPickerOpen}
        isTextInputFocused={isTextInputFocused}
        setIsTextInputFocused={setIsTextInputFocused}
        handleSendMessage={handleSendMessage}
        handleKeyDown={handleKeyDown}
        handleAdditionalFeatureClick={handleAdditionalFeatureClick}
        toggleEmojiPicker={toggleEmojiPicker}
        handleFocusInput={handleFocusInput}
        textareaRef={textareaRef}
        emojiButtonRef={emojiButtonRef}
      />
    </div>
  );
};

export default ChatApp;
